<?php
namespace app\modules\api\models;

use yii;
use yii\db\Query;

class Customer
{
    private $table;

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix.'customer';
    }

    public function list($p, $s, $where)
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if ($where['customer_group']) {
            $db->andWhere(['customer_group'=>$where['customer_group']]);
        }

        if ($where['follow_man']) {
            $db->andWhere(['follow_man'=>$where['follow_man']]);
        }

        if ($where['customer_status']) {
            $db->andWhere(['customer_status'=>$where['customer_status']]);
        }

        if ($where['refer']) {
            $db->andWhere(['refer'=>$where['refer']]);
        }

        if ($where['property']) {
            $db->andWhere(['property'=>$where['property']]);
        }
        
        if ($where['customer_name']) {
            $db->andWhere(['like','customer_name',$where['customer_name']]);
        }

        return $db->orderBy(['id'=>SORT_DESC])->offset(($p-1)*$s)->limit($s)->all();
    }

    public function size($where = [])
    {
        $db = new Query();
        $db->select('count(*) as num')->from($this->table);
        if ($where['customer_group']) {
            $db->andWhere(['customer_group'=>$where['customer_group']]);
        }

        if ($where['follow_man']) {
            $db->andWhere(['follow_man'=>$where['follow_man']]);
        }

        if ($where['customer_status']) {
            $db->andWhere(['customer_status'=>$where['customer_status']]);
        }

        if ($where['refer']) {
            $db->andWhere(['refer'=>$where['refer']]);
        }

        if ($where['property']) {
            $db->andWhere(['property'=>$where['property']]);
        }
        
        if ($where['customer_name']) {
            $db->andWhere(['like','customer_name',$where['customer_name']]);
        }

        $re = $db->one();
        return $re?$re['num']:0;
    }
}
